<template>
	<view class="order-detail-container page-container-with-bottom-btn">

		<!-- 订单状态 -->
		<view class="status-section">
			<view class="status-icon">
				<u-icon :name="getStatusIcon(orderInfo.order_status)" size="48"
					:color="getStatusColor(orderInfo.order_status)"></u-icon>
			</view>
			<view class="status-info">
				<text class="status-text">{{ orderInfo.order_status_desc }}</text>
				<text class="status-desc">{{ getStatusDesc(orderInfo.order_status) }}</text>
			</view>
		</view>

		<!-- 物流信息(可能有多个包裹) -->
		<block v-if="orderInfo.logistics && orderInfo.logistics.length>0">
			<view class="logistics-section" v-for="wlitem in orderInfo.logistics" :key="wlitem.id"
				@click="toLogistics(wlitem)">
				<view class="logistics-header">
					<view class="logistics-left">
						<u-icon name="car" size="24" color="#1c705e"></u-icon>
						<view class="logistics-info">
							<text class="logistics-company">{{ wlitem.lc_name }}</text>
							<text class="logistics-no">运单号：{{ wlitem.track_no }}（包裹{{wlitem.package_seq}}）</text>
						</view>
					</view>
					<u-icon name="arrow-right" size="16" color="#999"></u-icon>
				</view>
				<view class="logistics-progress">
					<text class="progress-text">{{ wlitem.logistics_status_desc }}</text>
					<text class="progress-time">{{ wlitem.last_logistics_time }}</text>
				</view>
			</view>
		</block>

		<!-- 收货地址 -->
		<view v-if="orderInfo.receive_type===1" class="address-section">
			<view class="address-header">
				<u-icon name="map" size="20" color="#1c705e"></u-icon>
				<text class="address-title">收货地址</text>
			</view>
			<view class="address-content">
				<view class="address-info">
					<text class="receiver-name">{{ orderInfo.receiver_name }}</text>
					<text class="receiver-phone">{{ orderInfo.receiver_phone_hidden }}</text>
				</view>
				<text
					class="address-detail">{{ orderInfo.pcs+' '+$secret.decryptAES(orderInfo.receiver_address) }}</text>
			</view>
		</view>
		<view v-else-if="orderInfo.self_pickup_status>=1 && orderInfo.self_pickup_code!==''" class="address-section">
			<view class="address-header">
				<u-icon name="map" size="20" color="#1c705e"></u-icon>
				<text class="address-title">核销码</text>
			</view>
			<view class="qrcode-container">
				<canvas canvas-id="qrcode" :style="{ width: (size+40) + 'rpx', height: (size+40) + 'rpx' }"
					class="qr-canvas" />
				<text class="qrcode-label">{{$secret.decryptAES(orderInfo.self_pickup_code)}}</text>
			</view>
			<view v-if="orderInfo.self_pickup_status===2" class="product-info" style="margin-top: 10px;">
				<text class="product-name">{{ orderInfo.self_pickup_by }}</text>
				<text class="product-spec">{{ orderInfo.self_pickup_time }}</text>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="product-section">
			<view class="section-header">
				<text class="section-title">商品信息</text>
			</view>
			<view class="product-list">
				<view class="product-item" v-for="(product, index) in orderInfo.products" :key="index"
					@click="toProductDetail(product)">
					<image :src="$tools.buildUrl(product.main_image)" mode="aspectFill" class="product-image"></image>
					<view class="product-info">
						<text class="product-name">{{ product.spu_name }}</text>
						<text class="product-spec">{{ product.sku_name }}</text>
						<view class="product-bottom">
							<text class="product-price">¥{{ product.actual_price }}</text>
							<text class="product-quantity">x{{ product.quantity }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 订单信息 -->
		<view class="order-section">
			<view class="section-header">
				<text class="section-title">订单信息</text>
			</view>
			<view class="order-info">
				<view class="info-item">
					<text class="info-label">订单号</text>
					<text class="info-value">{{ orderInfo.order_no }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">下单时间</text>
					<text class="info-value">{{ orderInfo.create_time }}</text>
				</view>
				<view class="info-item" v-if="orderInfo.pay_time">
					<text class="info-label">支付时间</text>
					<text class="info-value">{{ orderInfo.pay_time }}</text>
				</view>
				<view class="info-item" v-if="orderInfo.ship_time">
					<text class="info-label">发货时间</text>
					<text class="info-value">{{ orderInfo.ship_time }}</text>
				</view>
				<view class="info-item" v-if="orderInfo.receive_time">
					<text class="info-label">收货时间</text>
					<text class="info-value">{{ orderInfo.receive_time }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">支付方式</text>
					<text class="info-value">{{ orderInfo.pay_type_desc }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">配送方式</text>
					<text class="info-value">{{ orderInfo.receive_type===1?'快递配送':'用户自提' }}</text>
				</view>
				<view class="info-item" v-if="orderInfo.buyer_words">
					<text class="info-label">订单备注</text>
					<text class="info-value">{{ orderInfo.buyer_words }}</text>
				</view>
			</view>
		</view>

		<!-- 费用明细 -->
		<view class="cost-section">
			<view class="section-header">
				<text class="section-title">费用明细</text>
			</view>
			<view class="cost-info">
				<view class="cost-item">
					<text class="cost-label">商品总价</text>
					<text class="cost-value">¥{{ orderInfo.goods_amount }}</text>
				</view>
				<view class="cost-item">
					<text class="cost-label">运费</text>
					<text class="cost-value">{{ orderInfo.post_amount > 0 ? `¥${orderInfo.post_amount}` : '免费' }}</text>
				</view>
				<view class="cost-item" v-if="orderInfo.shop_cost_amount > 0">
					<text class="cost-label">优惠金额</text>
					<text class="cost-value discount">-¥{{ orderInfo.shop_cost_amount }}</text>
				</view>
				<view class="cost-item total">
					<text class="cost-label">订单金额</text>
					<text class="cost-value">¥{{ orderInfo.pay_amount }}</text>
				</view>
			</view>
		</view>

		<!-- 底部操作 -->
		<view class="bottom-actions" v-if="hasActions">
			<button class="action-btn secondary" v-if="orderInfo.order_status === 0" @click="cancelOrder">
				取消订单
			</button>
			<button class="action-btn primary" v-if="orderInfo.order_status === 0" @click="payOrder">
				立即支付
			</button>
			<button class="action-btn secondary" v-if="[4,5].includes(orderInfo.order_status)" @click="confirmReceive">
				确认收货
			</button>
			<button class="action-btn secondary" v-if="orderInfo.order_status === 7 && orderInfo.comment_count<=0"
				@click="evaluateOrder">
				评价订单
			</button>
			<button class="action-btn secondary" v-if="canAfterSales" @click="applyAfterSales">
				申请售后
			</button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import UQRCode from 'uqrcodejs';
	export default {
		data() {
			return {
				size: 200,
				orderId: '',
				orderInfo: {}
			}
		},
		computed: {
			...mapGetters(['userInfo', 'dealerInfo']),
			// 是否有操作按钮
			// 订单状态：0-待确认/待支付（订单创建完毕）2-已支付 3-备货中 4-部分发货 5-已发货（全部发货）6-已取消 7-已完成（已收货）
			hasActions() {
				return [0, 2, 4, 5].includes(this.orderInfo.order_status) || this.canAfterSales
			},
			// 是否可以申请售后
			canAfterSales() {
				return [2, 3, 4, 5, 7].includes(this.orderInfo.order_status)
			}
		},
		onLoad(options) {
			if (options.orderId) {
				this.orderId = options.orderId
				this.loadOrderDetail()
			}
		},
		methods: {
			// 加载订单详情
			loadOrderDetail() {
				this.$api.order.GetOrdersInfo({
					id: this.orderId
				}).then(res => {
					const province = this.$tools.parseJsonObject(res.data.receiver_province)
					const city = this.$tools.parseJsonObject(res.data.receiver_city)
					const town = this.$tools.parseJsonObject(res.data.receiver_town)
					this.orderInfo = res.data;
					if (province && province.name) {
						this.orderInfo.pcs = province.name + city.name + town.name;
					} else {
						this.orderInfo.pcs = ''
					}
					const shipPackage = this.orderInfo.logistics.find(item => item.ship_time && item.ship_time !==
						'');
					const recvPackage = this.orderInfo.logistics.find(item => item.receive_time && item
						.receive_time !== '');
					if (shipPackage) {
						this.orderInfo.ship_time = shipPackage.ship_time
					}
					if (recvPackage) {
						this.orderInfo.receive_time = recvPackage.receive_time
					}

					this.generateQRCode()
				})
			},

			// 获取状态图标
			getStatusIcon(status) {
				const iconMap = {
					0: 'clock',
					2: 'checkmark-circle',
					3: 'checkmark-circle',
					4: 'car',
					5: 'car',
					7: 'home',
					6: 'close-circle'
				}
				return iconMap[status] || 'help-circle'
			},

			// 获取状态颜色
			getStatusColor(status) {
				const colorMap = {
					0: '#856404',
					2: '#0c5460',
					3: '#856404',
					4: '#856404',
					5: '#856404',
					7: '#155724',
					6: '#721c24'
				}
				return colorMap[status] || '#999'
			},

			// 获取状态文本（未启用）
			getStatusText(status) {
				const textMap = {
					0: '待付款',
					2: '待发货',
					3: '备货中',
					4: '已发货',
					5: '待收货',
					7: '已完成',
					6: '已取消'
				}
				return textMap[status] || '未知状态'
			},

			// 获取状态描述  0-待确认/待支付（订单创建完毕）2-已支付 3-备货中 4-部分发货 5-已发货（全部发货）6-已取消 7-已完成（已收货）
			getStatusDesc(status) {
				const descMap = {
					0: '等待客户付款',
					1: '等待客户付款',
					2: '商家正在准备发货',
					3: '商家正在准备发货',
					4: '商品正在配送中',
					5: '商品正在配送中',
					7: '订单已完成，感谢您的购买',
					6: '订单已取消'
				}
				return descMap[status] || ''
			},

			// 跳转到物流详情
			toLogistics(wlitem) {
				uni.navigateTo({
					url: `/pages/order/logistics?orderId=${this.orderId}&logistics_id=${wlitem.id}`
				})
			},

			// 跳转到商品详情
			toProductDetail(product) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${product.spu_id}&sku_id=${product.sku_id}`
				})
			},

			// 取消订单
			cancelOrder() {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消这个订单吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.order.CancelOrders({
								id: this.orderInfo.id
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								this.loadOrderDetail()

								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								if (prevPage) {
									prevPage.$vm.setOrderStatus(this.orderId, this.orderInfo
										.order_status, this.orderInfo.order_status_desc)
								}
							})
						}
					}
				})
			},

			// 支付订单
			payOrder() {
				uni.navigateTo({
					url: `/pages/order/payment?order_ids=${this.orderId}&type=pay`
				})
			},

			// 确认收货
			confirmReceive() {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.order.ReceiverOrders({
								id: this.orderInfo.id
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								this.loadOrderDetail()

								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								if (prevPage) {
									prevPage.$vm.setOrderStatus(this.orderId, this.orderInfo
										.order_status, this.orderInfo.order_status_desc)
								}
							})
						}
					}
				})
			},

			// 评价订单
			evaluateOrder() {
				uni.navigateTo({
					url: `/pages/order/evaluate?orderId=${this.orderId}`
				})
			},

			// 申请售后
			applyAfterSales() {
				uni.navigateTo({
					url: `/pages/after-sale/apply?orderId=${this.orderId}`
				})
			},

			// 更新评价状态
			setComment() {
				this.orderInfo.comment_count++
			},

			// 订单核销码（订单ID+核销码）
			generateQRCode() {
				if (!(this.orderInfo.receive_type === 2 && this.orderInfo.self_pickup_code != '')) {
					return
				}
				const pickupQrCode = this.orderInfo.id + this.$secret.decryptAES(this.orderInfo.self_pickup_code)
				const qr = new UQRCode();
				qr.data = pickupQrCode; // 二维码内容
				qr.size = 130; // 尺寸需与 canvas 一致
				qr.margin = 5;
				qr.foregroundColor = '#000000';
				qr.backgroundColor = '#FFFFFF';

				// 添加logo
				// 最佳实践：
				// 1. 尺寸：80×80像素
				// 2. 格式：PNG（带透明背景）
				// 3. 颜色：单色或简单双色
				let logoUrl = this.$tools.buildUrl('/static/images/product.png')
				if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
					logoUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
				}
				if (logoUrl && logoUrl != '') {
					qr.logo = logoUrl;
					qr.logoScale = 0.2; // logo占二维码比例										
				}

				qr.make(); // 生成二维码
				const ctx = uni.createCanvasContext('qrcode', this); // 组件需传 this
				qr.canvasContext = ctx;
				qr.drawCanvas();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-detail-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: calc(180rpx + env(safe-area-inset-bottom));
	}

	.status-section {
		background-color: #ffffff;
		padding: 40rpx 30rpx;
		margin: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		display: flex;
		align-items: center;
	}

	.status-icon {
		margin-right: 30rpx;
	}

	.status-info {
		flex: 1;
	}

	.status-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.status-desc {
		font-size: 26rpx;
		color: #666;
		display: block;
	}

	.logistics-section {
		background-color: #ffffff;
		padding: 40rpx;
		margin-bottom: 20rpx;
	}

	.logistics-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.logistics-left {
		display: flex;
		align-items: center;
	}

	.logistics-info {
		margin-left: 16rpx;
	}

	.logistics-company {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.logistics-no {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	.logistics-progress {
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 12rpx;
	}

	.progress-text {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.progress-time {
		font-size: 24rpx;
		color: #666;
		display: block;
	}

	.address-section,
	.product-section,
	.order-section,
	.cost-section {
		background-color: #ffffff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.address-title {
		font-size: 28rpx;
		color: #333;
		margin-left: 12rpx;
	}

	.address-content {
		padding-left: 32rpx;
	}

	.address-info {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.receiver-name {
		font-size: 28rpx;
		color: #333;
		margin-right: 20rpx;
	}

	.receiver-phone {
		font-size: 28rpx;
		color: #666;
	}

	.address-detail {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
	}

	.section-header {
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.product-list {
		margin-top: 20rpx;
	}

	.product-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.product-item:last-child {
		margin-bottom: 0;
	}

	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
	}

	.product-info {
		flex: 1;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
		display: block;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 16rpx;
		display: block;
	}

	.product-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-price {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff4757;
	}

	.product-quantity {
		font-size: 24rpx;
		color: #666;
	}

	.order-info,
	.cost-info {
		margin-top: 20rpx;
	}

	.info-item,
	.cost-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.info-item:last-child,
	.cost-item:last-child {
		margin-bottom: 0;
	}

	.cost-item.total {
		padding-top: 20rpx;
		border-top: 1rpx solid #eee;
	}

	.info-label,
	.cost-label {
		font-size: 26rpx;
		color: #666;
	}

	.info-value,
	.cost-value {
		font-size: 26rpx;
		color: #333;
	}

	.cost-value.discount {
		color: #ff4757;
	}

	.cost-item.total .cost-label,
	.cost-item.total .cost-value {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff4757;
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1rpx solid #eee;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		display: flex;
		gap: 16rpx;
	}

	.action-btn {
		flex: 1;
		border: none;
		border-radius: 20rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
		font-weight: 500;
		min-width: 120rpx;
		text-align: center;
	}

	.action-btn.primary {
		background-color: #52a58a;
		color: #ffffff;
	}

	.action-btn.secondary {
		background-color: transparent;
		color: #666;
		border: 1rpx solid #ddd;
	}

	.qrcode-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 15rpx;
	}

	.qr-canvas {
		/* 确保 Canvas 可见 */
		display: block;
		background: white;
	}

	.qrcode-label {
		font-size: 48rpx;
		color: #666;
		text-align: center;
	}
</style>